package cn.edu.zjicm.wordsnet_d.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.adapter.SchoolRankAdapter;
import cn.edu.zjicm.wordsnet_d.adapter.SchoolRankPagerAdapter;
import cn.edu.zjicm.wordsnet_d.data.BoardItem;
import cn.edu.zjicm.wordsnet_d.data.BoardList;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.synchronize.LeaderBoardInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;
import cn.edu.zjicm.wordsnet_d.view.ShareDialog;
import cn.edu.zjicm.wordsnet_d.view.pageindicator.PageIndicator;

public class LeaderboardActivity extends WordBaseActivity {

	public static void startActivity(Context context) {
		Intent in = new Intent(context, LeaderboardActivity.class);
		context.startActivity(in);
	}

	private ViewPager mViewPager;
	private SchoolRankPagerAdapter mPagerAdapter;
	private PageIndicator mPageIndicator;
	private MyDialog addSchoolDialog;
	private boolean[] hasLoaded = new boolean[] { false, false, false };
	private int[] myRank = new int[] { 0, 0, 0 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leader_board);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("校园排行榜");
		setRightButton1("", R.drawable.calendar_info_selector, clickListener);
		setRightText2("", R.drawable.title_bar_share_button_selector, shareClickListener);
		findView();
		initView();
	}

	OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			ShowRegularActivity.startActivity(LeaderboardActivity.this, ShowRegularActivity.TYPE_LEADER_BOARD);
		}
	};

	OnClickListener shareClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			int currentItem = mViewPager.getCurrentItem();
			switch (currentItem) {
			case 0:
				if (hasLoaded[0]) {
					new ShareDialog(LeaderboardActivity.this, Utils.shareFrom.leardboardtab1, myRank[0]);
				} else {
					Toast.makeText(LeaderboardActivity.this, "打卡榜获加载数据失败", Toast.LENGTH_SHORT).show();
				}
				break;
			case 1:
				if (hasLoaded[1]) {
					new ShareDialog(LeaderboardActivity.this, Utils.shareFrom.leardboardtab2, myRank[1]);
				} else {
					Toast.makeText(LeaderboardActivity.this, "单词学习榜获加载数据失败", Toast.LENGTH_SHORT).show();
				}
				break;
			case 2:
				if (hasLoaded[2]) {
					new ShareDialog(LeaderboardActivity.this, Utils.shareFrom.leardboardtab3, myRank[2]);
				} else {
					Toast.makeText(LeaderboardActivity.this, "学校榜获加载数据失败", Toast.LENGTH_SHORT).show();
				}
				break;
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (AppPreference.getSchoolId(this) == -1) {
			if (addSchoolDialog != null && addSchoolDialog.isShowing()) {
			} else {
				showAddSchoolDialog();
			}
		} else {
			if (addSchoolDialog != null && addSchoolDialog.isShowing()) {
				addSchoolDialog.dismiss();
			}
			if (!hasLoaded[0]) {
				toGetUserBoard(LeaderBoardInterface.PUNCH_BOARD);
			}
		}
	}

	private void initView() {

		if (AppPreference.getSchoolId(this) == -1) {
			showAddSchoolDialog();
			setFakeData();
		} else {
			List<BoardItem> boardItemList = new ArrayList<BoardItem>();
			BoardList boardList = new BoardList(boardItemList, false, 0);
			mPagerAdapter = new SchoolRankPagerAdapter(this, boardList, false);
		}

		mViewPager.setOffscreenPageLimit(3);
		mViewPager.setAdapter(mPagerAdapter);
		mPageIndicator.setViewPager(mViewPager);

		mPageIndicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				if (!hasLoaded[position]) {
					switch (position) {
					case 0:
						toGetUserBoard(LeaderBoardInterface.PUNCH_BOARD);
						break;
					case 1:
						toGetUserBoard(LeaderBoardInterface.EXP_BOARD);
						break;
					case 2:
						toGetSchoolBoard();
						break;
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	private void findView() {
		mViewPager = (ViewPager) findViewById(R.id.school_view_pager);
		mPageIndicator = (PageIndicator) findViewById(R.id.school_pager_indicator);
	}

	private void showAddSchoolDialog() {

		View addSchoolView = LayoutInflater.from(this).inflate(R.layout.view_add_school, null);
		Button addSchoolBtn = (Button) addSchoolView.findViewById(R.id.add_school_btn);
		addSchoolDialog = new MyDialog(this, addSchoolView, R.style.mydialog, false);
		addSchoolDialog.setCanceledOnTouchOutside(false);
		addSchoolBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				AddSchoolActivity.startActivity(LeaderboardActivity.this);
			}
		});
		addSchoolDialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					addSchoolDialog.dismiss();
					LeaderboardActivity.this.finish();
					return true;
				}
				return false;
			}
		});
		addSchoolDialog.show();
	}

	private void setFakeData() {
		List<BoardItem> boardItemList = new ArrayList<BoardItem>();
		int[] rank = new int[] { 120, 1, 2, 3, 118, 119, 120, 121, 122 };
		String[] name = new String[] { "落花、笑意", "掩饰的心伤", "莪、（寂寞）", "回忆,划下伤口", "唐唐", "独你暖光", "落花、笑意", "何去何从、", "緈福，好远" };
		int[] score = new int[] { 320, 640, 602, 580, 459, 368, 320, 287, 106 };
		BoardItem boardItem;
		for (int i = 0; i < score.length; i++) {
			boardItem = new BoardItem(rank[i], name[i], score[i]);
			boardItemList.add(boardItem);
		}
		BoardList boardList = new BoardList(boardItemList, true, 120);
		mPagerAdapter = new SchoolRankPagerAdapter(this, boardList, true);
	}

	// type: LeaderBoardInterface.PUNCH_BOARD 获取打卡榜;
	// LeaderBoardInterface.EXP_BOARD 获取单词学习榜
	public void toGetUserBoard(int type) {
		Handler handler = null;
		if (type == LeaderBoardInterface.PUNCH_BOARD)
			handler = getUserPunchHandler;
		else if (type == LeaderBoardInterface.EXP_BOARD)
			handler = getUserExpHandler;

		handler.sendMessage(handler.obtainMessage(UserInterface.MSG_START));
		LeaderBoardInterface.getInstance(LeaderboardActivity.this).getUserBoard(type, handler);
	}

	GetUserBoardHandler getUserPunchHandler = new GetUserBoardHandler(LeaderBoardInterface.PUNCH_BOARD);
	GetUserBoardHandler getUserExpHandler = new GetUserBoardHandler(LeaderBoardInterface.EXP_BOARD);

	ProgressDialog dialog2 = null;

	class GetUserBoardHandler extends Handler {
		int type;

		// ProgressDialog dialog2 = null;

		GetUserBoardHandler(int type) {
			this.type = type;
		}

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START) {
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}
			}
			switch (msg.what) {
			case UserInterface.MSG_START:
				if (type == LeaderBoardInterface.PUNCH_BOARD)
					dialog2 = ProgressDialog.show(LeaderboardActivity.this, null, "正在获取打卡榜信息");
				else if (type == LeaderBoardInterface.EXP_BOARD)
					dialog2 = ProgressDialog.show(LeaderboardActivity.this, null, "正在获取单词学习榜");
				dialog2.setOnKeyListener(onKeyListener);
				isLive[mViewPager.getCurrentItem()] = true;
				break;
			case UserInterface.MSG_SUCCESS:
				BoardList schollList = (BoardList) msg.obj;
				schollList.filter(); // 筛选出前3和本人前后各5名
				if (type == LeaderBoardInterface.PUNCH_BOARD) {
					mPagerAdapter.updateListData(schollList, SchoolRankAdapter.INDEX_PUNCHOUT);// 更新打卡榜
					hasLoaded[0] = true;
					myRank[0] = schollList.getMyRank();
					// Toast.makeText(LeaderboardActivity.this, "打卡排名" +
					// myRank[0], Toast.LENGTH_SHORT).show();
				} else if (type == LeaderBoardInterface.EXP_BOARD) {
					mPagerAdapter.updateListData(schollList, SchoolRankAdapter.INDEX_WORD);// 更新单词学习榜
					hasLoaded[1] = true;
					myRank[1] = schollList.getMyRank();
					// Toast.makeText(LeaderboardActivity.this, "单词学习排名" +
					// myRank[1], Toast.LENGTH_SHORT).show();
				}
				break;
			case UserInterface.MSG_UNSUCCESS:
				if (isLive[mViewPager.getCurrentItem()]) {
					if (type == LeaderBoardInterface.PUNCH_BOARD)
						Toast.makeText(LeaderboardActivity.this, "获取打卡榜失败，请稍后再试", Toast.LENGTH_SHORT).show();
					else if (type == LeaderBoardInterface.EXP_BOARD)
						Toast.makeText(LeaderboardActivity.this, "获取单词学习榜失败，请稍后再试", Toast.LENGTH_SHORT).show();
					showBadNetwork(type);
				}
				break;
			case UserInterface.MSG_BAD_NETWORK:
				if (isLive[mViewPager.getCurrentItem()]) {
					Toast.makeText(LeaderboardActivity.this, "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
					showBadNetwork(type);
				}
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				if (isLive[mViewPager.getCurrentItem()]) {
					Toast.makeText(LeaderboardActivity.this, "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
					showBadNetwork(type);
				}
				break;
			}
		};
	};

	private void showBadNetwork(int type) {
		if (type == LeaderBoardInterface.PUNCH_BOARD) {
			mPagerAdapter.showBadNetwork(0);
		} else if (type == LeaderBoardInterface.EXP_BOARD) {
			mPagerAdapter.showBadNetwork(1);
		}
	}

	public void toGetSchoolBoard() {
		getSchoolBoardHandler.sendMessage(getSchoolBoardHandler.obtainMessage(UserInterface.MSG_START));
		LeaderBoardInterface.getInstance(LeaderboardActivity.this).getSchoolBoard(getSchoolBoardHandler);
	}

	Handler getSchoolBoardHandler = new Handler() {
		// ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START) {
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}
			}
			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(LeaderboardActivity.this, null, "正在获取学校榜信息");
				dialog2.setOnKeyListener(onKeyListener);
				isLive[mViewPager.getCurrentItem()] = true;
				break;
			case UserInterface.MSG_SUCCESS:
				// LogUtil.d("Tag", "activity中obj="+msg.obj);
				BoardList schollList = (BoardList) msg.obj;
				// LogUtil.d("Tag",
				// "activity中schoolList.size="+schollList.size()); // 更新校园榜
				schollList.filter(); // 筛选出前3和本人前后各5名
				mPagerAdapter.updateListData(schollList, SchoolRankAdapter.INDEX_SCHOOL); // 更新打卡榜
				hasLoaded[2] = true;
				myRank[2] = schollList.getMyRank();
				// Toast.makeText(LeaderboardActivity.this, "学校排名" + myRank[2],
				// Toast.LENGTH_SHORT).show();
				break;
			case UserInterface.MSG_UNSUCCESS:
				if (isLive[mViewPager.getCurrentItem()]) {
					Toast.makeText(LeaderboardActivity.this, "获取校园榜失败，请稍后再试", Toast.LENGTH_SHORT).show();
					mPagerAdapter.showBadNetwork(2);
				}
				break;
			case UserInterface.MSG_BAD_NETWORK:
				if (isLive[mViewPager.getCurrentItem()]) {
					Toast.makeText(LeaderboardActivity.this, "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
					mPagerAdapter.showBadNetwork(2);
				}
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				if (isLive[mViewPager.getCurrentItem()]) {
					Toast.makeText(LeaderboardActivity.this, "网络未连接，提交失败，请稍后再试", Toast.LENGTH_SHORT).show();
					mPagerAdapter.showBadNetwork(2);
				}
				break;
			}
		};
	};

	private OnKeyListener onKeyListener = new OnKeyListener() {
		@Override
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
				dismissDialogAndFinish();
			}
			return false;
		}
	};

	boolean isLive[] = { true, true, true };

	public void dismissDialogAndFinish() {
		if (isFinishing()) {
			return;
		}
		if (null != dialog2 && dialog2.isShowing()) {
			dialog2.dismiss();
		}
		mPagerAdapter.showBadNetwork(mViewPager.getCurrentItem());
		isLive[mViewPager.getCurrentItem()] = false;
		// if(mViewPager.getCurrentItem() == 0)
		// getUserPunchHandler.removeMessages(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE);
		// else if(mViewPager.getCurrentItem() == 1)
		// getUserExpHandler.removeMessages(UserInterface.MSG_WEB_SITE_ACCESS_FAILURE);
		// else if(mViewPager.getCurrentItem() == 2)
		// getSchoolBoardHandler.removeCallbacks(r)
		// finish();
	}
}
